/* Includes--------------------------------------------- */
#include "pwm.h"
#include "gd32e23x.h"

/* Define----------------------------------------------- */
#define TIMER_PERIPH        TIMER2
#define TIMER_CLOCK     RCU_TIMER2
#define TIMER_CHANNEL   TIMER_CH_3
#define TIMER_PERIOD         15999

/* Private funtion delaration--------------------------- */
static timer_parameter_struct pwm_initpara;
static timer_oc_parameter_struct pwm_ocpara;

/* Private variables------------------------------------ */
/* External variables----------------------------------- */
/* External functions----------------------------------- */
void DrvPWMInit(void) {
  rcu_periph_clock_enable(RCU_GPIOB);
  gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_1);
  gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_1);
  gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_1);

  rcu_periph_clock_enable(TIMER_CLOCK);
  timer_deinit(TIMER_PERIPH);
  timer_struct_para_init(&pwm_initpara);

  pwm_initpara.prescaler = 1;
  pwm_initpara.alignedmode = TIMER_COUNTER_EDGE;
  pwm_initpara.counterdirection = TIMER_COUNTER_UP;
  pwm_initpara.period = TIMER_PERIOD;
  pwm_initpara.clockdivision = TIMER_CKDIV_DIV1;
  pwm_initpara.repetitioncounter = 0;
  timer_init(TIMER_PERIPH, &pwm_initpara);

  timer_channel_output_struct_para_init(&pwm_ocpara);
  pwm_ocpara.outputstate = TIMER_CCX_DISABLE;
  pwm_ocpara.outputnstate = TIMER_CCXN_ENABLE;
  pwm_ocpara.ocpolarity = TIMER_OC_POLARITY_HIGH;
  pwm_ocpara.ocnpolarity = TIMER_OCN_POLARITY_HIGH;
  pwm_ocpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
  pwm_ocpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
  timer_channel_output_config(TIMER_PERIPH, TIMER_CHANNEL, &pwm_ocpara);

  timer_channel_output_mode_config(TIMER_PERIPH, TIMER_CHANNEL, TIMER_OC_MODE_PWM0);
  timer_channel_output_pulse_value_config(TIMER_PERIPH, TIMER_CHANNEL, 4000);
  timer_channel_output_shadow_config(TIMER_PERIPH, TIMER_CHANNEL, TIMER_OC_SHADOW_ENABLE);

  timer_auto_reload_shadow_enable(TIMER_PERIPH);
  timer_enable(TIMER_PERIPH);
}

void DrvPWMRefresh(uint16_t value) {
  timer_channel_output_pulse_value_config(TIMER_PERIPH, TIMER_CHANNEL, TIMER_PERIOD * value / 65535);
}

/* Private functions------------------------------------ */
/* End of file------------------------------------------ */
